<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-logo">
        <img src="../assets/logo.png" alt="Logo">
        <h1>排队叫号系统</h1>
      </div>
      <el-tabs v-model="activeTab" class="login-tabs">
        <el-tab-pane label="登录" name="login">
          <el-form
            ref="loginFormRef"
            :model="loginForm"
            :rules="loginRules"
            class="login-form"
          >
            <el-form-item prop="username">
              <el-input
                v-model="loginForm.username"
                placeholder="用户名"
                prefix-icon="User"
              >
              </el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                v-model="loginForm.password"
                placeholder="密码"
                show-password
                type="password"
                @keyup.enter="handleLogin"
              >
                <template #prefix>
                  <el-icon><Lock /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                :loading="loading"
                class="login-button"
                @click="handleLogin"
              >
                登录
              </el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="注册" name="register">
          <el-form
            ref="registerFormRef"
            :model="registerForm"
            :rules="registerRules"
            class="login-form"
          >
            <el-form-item prop="username">
              <el-input
                v-model="registerForm.username"
                placeholder="用户名"
                prefix-icon="User"
              >
              </el-input>
            </el-form-item>
            <el-form-item prop="name">
              <el-input
                v-model="registerForm.name"
                placeholder="姓名"
                prefix-icon="User"
              >
              </el-input>
            </el-form-item>
            <el-form-item prop="phone">
              <el-input
                v-model="registerForm.phone"
                placeholder="手机号"
                prefix-icon="Phone"
              >
              </el-input>
            </el-form-item>
            <el-form-item prop="email">
              <el-input
                v-model="registerForm.email"
                placeholder="邮箱"
                prefix-icon="Message"
              >
              </el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                v-model="registerForm.password"
                placeholder="密码"
                show-password
                type="password"
              >
              </el-input>
            </el-form-item>
            <el-form-item prop="confirmPassword">
              <el-input
                v-model="registerForm.confirmPassword"
                placeholder="确认密码"
                show-password
                type="password"
              >
                <template #prefix>
                  <el-icon><Lock /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                :loading="registerLoading"
                class="login-button"
                @click="handleRegister"
              >
                注册
              </el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
      <div class="login-footer">
        <p>© {{ new Date().getFullYear() }} 排队叫号系统管理后台</p>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Lock } from '@element-plus/icons-vue'
import axios from "axios";

export default {
  name: 'Login',
  components: {
    Lock,
  },
  setup() {
    const router = useRouter()
    const route = useRoute()
    const loginFormRef = ref(null)
    const registerFormRef = ref(null)
    const loading = ref(false)
    const registerLoading = ref(false)
    const activeTab = ref('login')

    const loginForm = reactive({
      username: '',
      password: ''
    })

    const registerForm = reactive({
      username: '',
      name: '',
      phone: '',
      email: '',
      password: '',
      confirmPassword: ''
    })

    const loginRules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
      ]
    }

    const registerRules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
      ],
      name: [
        { required: true, message: '请输入姓名', trigger: 'blur' }
      ],
      phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
      ],
      email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, message: '密码长度不能少于6个字符', trigger: 'blur' }
      ],
      confirmPassword: [
        { required: true, message: '请再次输入密码', trigger: 'blur' },
        {
          validator: (rule, value, callback) => {
            if (value !== registerForm.password) {
              callback(new Error('两次输入的密码不一致'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }
      ]
    }

    // 从localStorage获取已注册用户列表
    const getRegisteredUsers = () => {
      const usersStr = localStorage.getItem('registeredUsers')
      return usersStr ? JSON.parse(usersStr) : []
    }

    // 保存注册用户到localStorage
    const saveRegisteredUser = (user) => {
      const users = getRegisteredUsers()
      users.push(user)
      localStorage.setItem('registeredUsers', JSON.stringify(users))
    }

    // 处理注册
    const handleRegister = () => {
      registerFormRef.value.validate((valid) => {
        if (valid) {
          registerLoading.value = true
          registerLoading.value = false

          // 检查用户名是否已存在
          const users = getRegisteredUsers()
          const existingUser = users.find(user => user.username === registerForm.username)

          if (existingUser) {
            ElMessage.error('用户名已存在')
            return
          }

          // 创建新用户（默认为禁用状态）
          const newUser = {
            username: registerForm.username,
            name: registerForm.name,
            phone: registerForm.phone,
            email: registerForm.email,
            password: registerForm.password,
            roleId: 3, // 默认为窗口操作员角色
            roleName: '窗口操作员',
            status: 0, // 0-禁用，1-启用
            createTime: new Date().toISOString().replace('T', ' ').substring(0, 19),
            lastLoginTime: null
          }

          axios.post('/auth/register', newUser).then(() => {
            ElMessage.success('注册成功，请等待管理员审核后启用账号')

            // 清空表单并切换到登录页
            Object.keys(registerForm).forEach(key => {
              registerForm[key] = ''
            })

            activeTab.value = 'login'
          });
        }
      })
    }

    // 处理登录 - 使用模拟数据
    const handleLogin = () => {
      loginFormRef.value.validate((valid) => {
        if (valid) {
          loading.value = true
          axios.post('/auth/login', {
            username: loginForm.username,
            password: loginForm.password,
          }).then((res) => {
            console.log(res);
            loading.value = false
            // 用户名和密码验证规则：
            // 1. superadmin/123456 - 超级管理员
            // 2. admin/123456 - 管理员
            // 3. operator/123456 - 窗口操作员
            // 4. 检查注册用户
            let userRole = res.data.data.role;
            let userData = res.data.data.userInfo;
            console.log('设置用户信息');
            // 保存模拟token和用户信息到localStorage
            const expireTime = Date.now() + 24 * 60 * 60 * 1000; // 24小时后过期

            // 根据角色设置权限
            const permissions = [];
            if (userRole === 'superadmin') {
              // 超级管理员拥有所有权限
              permissions.push(
                  'dashboard',
                  'queue',
                  'business',
                  'statistics',
                  'system',
                  'user_manage',
                  'role_manage',
                  'system_config'
              );
            } else if (userRole === 'admin') {
              // 管理员拥有除了管理管理员以外的所有权限
              permissions.push(
                  'dashboard',
                  'queue',
                  'business',
                  'statistics',
                  'system',
                  'system_config'
              );
            } else if (userRole === 'operator') {
              // 窗口操作员只能看到叫号终端页面
              permissions.push('operator_terminal');
            }

            localStorage.setItem('token', res.data.data.token);
            localStorage.setItem('tokenHead', 'Bearer');
            localStorage.setItem('expireTime', expireTime);
            localStorage.setItem('userInfo', JSON.stringify({
              ...userData,
              permissions: permissions
            }));
            ElMessage.success('登录成功');
            console.log(permissions);
            // 根据角色跳转到相应页面
            if (userRole === 'operator') {
              // 窗口操作员直接跳转到叫号终端
              router.push('/callTerminal');
            } else {
              // 超级管理员和管理员跳转到后台管理页面
              const redirect = route.query.redirect || '/dashboard';
              router.push(redirect);
            }
          });
        }
      });
    }

    // 检查是否已经登录
    onMounted(() => {
      const token = localStorage.getItem('token')
      const expireTime = localStorage.getItem('expireTime')

      if (token && expireTime && parseInt(expireTime) > Date.now()) {
        // token未过期，直接跳转
        const redirect = route.query.redirect || '/'
        router.push(redirect)
      } else if (token) {
        // token过期，清除登录信息
        localStorage.removeItem('token')
        localStorage.removeItem('tokenHead')
        localStorage.removeItem('expireTime')
        localStorage.removeItem('userInfo')
      }
    })

    return {
      activeTab,
      loginFormRef,
      registerFormRef,
      loginForm,
      registerForm,
      loginRules,
      registerRules,
      loading,
      registerLoading,
      handleLogin,
      handleRegister
    }
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  width: 100%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: relative;
  overflow: hidden;
}

.login-container::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: url('../assets/login-bg.jpg') no-repeat center center;
  background-size: cover;
  opacity: 0.1;
}

.login-box {
  width: 450px;
  padding: 40px;
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 8px;
  box-shadow: 0 15px 30px rgba(0, 0, 0, 0.1);
  position: relative;
  z-index: 1;
  backdrop-filter: blur(10px);
}

.login-logo {
  text-align: center;
  margin-bottom: 20px;
}

.login-logo img {
  height: 60px;
}

.login-logo h1 {
  font-size: 24px;
  color: #333;
  margin-top: 10px;
  font-weight: 500;
}

.login-tabs {
  margin-bottom: 20px;
}

.login-form .el-input {
  height: 50px;
}

.login-form .el-input__wrapper {
  padding: 0 15px;
  box-shadow: none;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.login-form .el-input__inner {
  height: 48px;
  font-size: 16px;
}

.login-button {
  width: 100%;
  height: 50px;
  font-size: 16px;
  border-radius: 4px;
}

.login-footer {
  text-align: center;
  margin-top: 20px;
}

.login-footer p {
  color: #606266;
  font-size: 12px;
}
</style>
